﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SharingCenter.Web.Classes.Message
{
    using SharingCenter.Web.Classes;
    public static class MailOperations
    {
        public static Sc_MailTemplate GetMailTemplate(string context, string eventName)
        {
            try
            {
                Sc_MailTemplate template = scDataContext.Instance.Sc_MailTemplates.Single(d => (d.MailEventGroup.ToLower() == context.ToLower() &&
                           d.MailEventName.ToLower() == eventName.ToLower()));
                return template;
            }
            catch
            {
                return null;
            }
        }

        public static bool SendSystemMail(string context, string eventName, string to, Dictionary<string, string> replacement)
        {
            Sc_MailTemplate template = GetMailTemplate(context, eventName);
            if (template != null)
            {
                if (template.Enabled)
                {
                    IMessage msg = new SiteMailMessage();
                    replacement.Add("SiteName", Resources.Website.SiteName);
                    replacement.Add("SiteUrl", WebConsts.SITE_URL);
                    replacement.Add("Date", DateTime.Today.ToLongDateString());
                    replacement.Add("Time", DateTime.Now.ToString("HH:mm"));
                    msg.SendSystemMail(template.MailSubject, template.MailContent, to, replacement);
                }

                return true;
            }
            else
            {
                return false;
            }
        }

        public static void GetReplacedContent(ref string content, ref string title, Dictionary<string, string> replacement)
        {
            replacement.Add("SiteName", Resources.Website.SiteName);
            replacement.Add("SiteUrl", WebConsts.SITE_URL);
            replacement.Add("Date", DateTime.Today.ToLongDateString());
            replacement.Add("Time", DateTime.Now.ToString("HH:mm"));

            string key;
            foreach (KeyValuePair<string, string> p in replacement)
            {
                key = WebConsts.MAIL_PARAM_L_DELIMETER + p.Key + WebConsts.MAIL_PARAM_R_DELIMETER;
                content = content.Replace(key, p.Value);
                title = title.Replace(key, p.Value);
            }
        }

        
    }
}
